package com.example.wechatscancode.utils;


import android.util.Base64;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.AlgorithmParameters;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


/**
 * @Title ExcelUtil.java
 * @Package com.leadron.medibase.cloud.utils
 * @Description AES 加解密工具类
 * @Author <a href="mailto:wangh@leadron.com">Wangh</a>
 * @Date 2019-01-18
 * @Version V1.0
 * @Copyright (c) 2006-2019 Leadron Information Technoloy co.,Ltd. All rights reserved.
 */
public class AESUtil {

    private static final String ALGORITHM_NAME = "AES/CBC/PKCS7Padding";
    private static final String AES_NAME = "AES";
    private static final String CHARSET_NAME = "UTF-8";
    private static final String PROVIDER_NAME = BouncyCastleProvider.PROVIDER_NAME;

    private static final String AES_KEY = "aEdmu1bIROMDNksFE5qwmg==";
    private static final String AES_IV = "+Medibase_Jonathan_Swq!=";

    static {
        // BouncyCastle是一个开源的加解密解决方案，主页在http://www.bouncycastle.org/
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String encrypt(String data) {
        String result = "";
        String key = "aEdmu1bIROMDNksFE5qwmg==";
        String iv = "Medibase1Jonathan2Swq3==";

        String encodingFormat = CHARSET_NAME;
        try {
            result = encrypt(data, key, iv, encodingFormat);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * AES加密
     *
     * @param data           //密文，要加密的数据
     * @param key            //秘钥
     * @param iv             //偏移量
     * @param encodingFormat //加密后的结果需要进行的编码
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key, String iv, String encodingFormat) throws Exception {
        // 被加密的数据
        byte[] dataByte = data.getBytes(encodingFormat);


        byte[] keyByte = Base64.decode(key, Base64.NO_WRAP);
        byte[] ivByte = Base64.decode(iv, Base64.NO_WRAP);


        try {
            // 加解密算法/模式/填充方式， 算法提供者
            Cipher cipher = Cipher.getInstance(ALGORITHM_NAME, PROVIDER_NAME);
            SecretKeySpec spec = new SecretKeySpec(keyByte, AES_NAME);
            AlgorithmParameters parameters = AlgorithmParameters.getInstance(AES_NAME);
            parameters.init(new IvParameterSpec(ivByte));
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                // 此处使用BAES64做转码功能，同时能起到2次加密的作用。
                String result = Base64.encodeToString(resultByte, Base64.NO_WRAP);
                return result;
            }

            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

//    public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
//    	// 被加密的数据
//        byte[] dataByte = org.apache.commons.codec.binary.Base64.decodeBase64(data);
//        // 加密秘钥
//        byte[] keyByte = org.apache.commons.codec.binary.Base64.decodeBase64(key);
//        // 偏移量
//        byte[] ivByte = org.apache.commons.codec.binary.Base64.decodeBase64(iv);
//
//        try {
//        	// 加解密算法/模式/填充方式， 算法提供者
//            Cipher cipher = Cipher.getInstance(ALGORITHM_NAME, PROVIDER_NAME);
//            SecretKeySpec spec = new SecretKeySpec(keyByte, AES_NAME);
//            AlgorithmParameters parameters = AlgorithmParameters.getInstance(AES_NAME);
//            parameters.init(new IvParameterSpec(ivByte));
//            // 初始化
//            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
//            byte[] resultByte = cipher.doFinal(dataByte);
//            if (null != resultByte && resultByte.length > 0) {
//                String result = new String(resultByte, encodingFormat);
//                return result;
//            }
//            return null;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }

    public static String getAlgorithmName() {
        return ALGORITHM_NAME;
    }

    public static String getAesName() {
        return AES_NAME;
    }

    public static String getCharsetName() {
        return CHARSET_NAME;
    }

    public static String getProviderName() {
        return PROVIDER_NAME;
    }

    public static String getAesKey() {
        return AES_KEY;
    }

    public static String getAesIv() {
        return AES_IV;
    }


    /**
     * @param args
     */
    public static void main(String[] args) {
        String key = "aEdmu1bIROMDNksFE5qwmg==";

        //String encryptData = "1B2FeurZBUzW1JbmNXolXrax43VFk5k1WHmJ1XWJOQ6wqdV/WD1HG19nz0d1L4ObJN5Nn2jOdXixtZ9n5xXyIMWvBI4VSyyp0PoY0ES+UAzsn4kOKfgI7B1Azb8wwafOJbXLxLSQ4kjxvwBzE9GzEEJ8Uq6DYKosLJFI+cfE9quBx7C3/A+uPOBgBMAlnLNE5pD0R5gagPIQgaBSX629Jg==";
        //String encryptData = "8WLqwf+GSrdGkabYGNp1Mt1fCX6hU2G/SyYjH+mCWKvNS57Bp0qjBtEvToWctEKl7X1XST2+OBWywi0DUkM8r8GGV6QkE8ItV8IBsWyjQ98sQZq3SgPvVzApczxdeSZ86ZIGXxT6c0ce3CQWn8s2S0fdR8hBVrnaRNkLyp/snPhTtbzpk7ZsBxaaAuHnEy+P2zJ7MAxO/WtPi1y0PkJ1CQ==";
        String encryptData = "BtEvToWctEKl7X1XST2+OBWywi0DUkM8r8GGV6QkE8ItV8IBsWyjQ98sQZq3SgPvVzApczxdeSZ86ZIGXxT6c0ce3CQWn8s2S0fdR8hBVrnaRNkLyp/snPhTtbzpk7ZsBxaaAuHnEy+P2zJ7MAxO/WtPi1y0PkJ1CQ==";

        //String iv = "hfdPHoxvrst26AcaR8JEDw==";
        String iv = "+Medibase_Jonathan_Swq!=";

        String encodingFormat = CHARSET_NAME;

        String decryptData = "{\"phoneNumber\":\"18827437765\",\"purePhoneNumber\":\"18827437765\",\"countryCode\":\"86\",\"watermark\":{\"timestamp\":1547886230,\"appid\":\"wx923c84e0ed1467e7\"}}";

        try {
            String s = AESUtil.encrypt(decryptData, key, iv, encodingFormat);
            System.out.println(s);
            System.out.println("加密数据与原数据对比测试结果：" + encryptData.equals(s));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String s = null;

//			s = AESUtil.decrypt(encryptData, key, iv, encodingFormat);
            System.out.println(s);
            if (null == s) {
                System.out.println("解密数据为空!");
            }
            System.out.println("解密数据与原数据对比测试结果：" + decryptData.equals(s));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}